<template>
  <div class="datasource-container">
    <NCard title="数据源管理" :bordered="false" class="h-full rounded-8px shadow-sm">
      <div class="h-full flex-col">
        <!-- 查询表单 -->
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NButton type="primary" @click="handleAdd">
              <template #icon>
                <icon-ic-round-plus class="text-icon" />
              </template>
              新增
            </NButton>
            <NButton type="error" :disabled="!selectedRowKeys.length" @click="handleBatchDelete">
              <template #icon>
                <icon-ic-round-delete class="text-icon" />
              </template>
              删除
            </NButton>
          </NSpace>
          <NSpace>
            <NButton @click="handleRefresh">
              <template #icon>
                <icon-mdi-refresh class="text-icon" />
              </template>
              刷新
            </NButton>
          </NSpace>
        </NSpace>

        <!-- 数据表格 -->
        <NDataTable
          :columns="columns"
          :data="dataSource"
          :loading="loading"
          :pagination="pagination"
          :row-key="(row: any) => row.id"
          :checked-row-keys="selectedRowKeys"
          @update:checked-row-keys="handleCheck"
          class="flex-1-hidden"
        />
      </div>
    </NCard>

    <!-- 新增/编辑对话框 -->
    <NModal v-model:show="showModal" :title="modalTitle" preset="card" class="w-700px">
      <NForm ref="formRef" :model="formData" :rules="formRules" label-placement="left" :label-width="100">
        <NFormItem label="数据源名称" path="name">
          <NInput v-model:value="formData.name" placeholder="请输入数据源名称" />
        </NFormItem>
        <NFormItem label="数据源类型" path="type">
          <NSelect v-model:value="formData.type" :options="dataSourceTypeOptions" placeholder="请选择数据源类型" />
        </NFormItem>
        <NFormItem label="主机地址" path="host">
          <NInput v-model:value="formData.host" placeholder="请输入主机地址" />
        </NFormItem>
        <NFormItem label="端口" path="port">
          <NInputNumber v-model:value="formData.port" placeholder="请输入端口" class="w-full" />
        </NFormItem>
        <NFormItem label="数据库名" path="databaseName">
          <NInput v-model:value="formData.databaseName" placeholder="请输入数据库名" />
        </NFormItem>
        <NFormItem label="用户名" path="username">
          <NInput v-model:value="formData.username" placeholder="请输入用户名" />
        </NFormItem>
        <NFormItem label="密码" path="password">
          <NInput
            v-model:value="formData.password"
            type="password"
            show-password-on="click"
            placeholder="请输入密码"
          />
        </NFormItem>
        <NFormItem label="状态" path="status">
          <NRadioGroup v-model:value="formData.status">
            <NRadio :value="1">启用</NRadio>
            <NRadio :value="0">禁用</NRadio>
          </NRadioGroup>
        </NFormItem>
        <NFormItem label="备注" path="remark">
          <NInput v-model:value="formData.remark" type="textarea" placeholder="请输入备注" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="handleTestConnection">测试连接</NButton>
          <NButton @click="showModal = false">取消</NButton>
          <NButton type="primary" @click="handleSubmit">确定</NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue';
import type { DataTableColumns, FormInst, FormRules } from 'naive-ui';
import { NButton, NSpace, NTag } from 'naive-ui';
import type { DataSource, DataSourceType } from '@/service/api/dataplatform/datasource';
import {
  getDataSourceList,
  addDataSource,
  updateDataSource,
  deleteDataSource,
  testDataSourceConnection,
  testConnection
} from '@/service/api/dataplatform/datasource';

defineOptions({
  name: 'DataPlatformDatasource'
});

// 数据源列表
const dataSource = ref<DataSource[]>([]);
const loading = ref(false);
const selectedRowKeys = ref<number[]>([]);

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 30, 50],
  onChange: (page: number) => {
    pagination.page = page;
    fetchData();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    fetchData();
  }
});

// 数据源类型选项
const dataSourceTypeOptions = [
  { label: 'MySQL', value: 'MYSQL' },
  { label: 'Oracle', value: 'ORACLE' },
  { label: 'PostgreSQL', value: 'POSTGRESQL' },
  { label: 'SQL Server', value: 'SQLSERVER' },
  { label: '达梦', value: 'DAMENG' },
  { label: '人大金仓', value: 'KINGBASE' },
  { label: 'Doris', value: 'DORIS' }
];

// 表格列配置
const columns: DataTableColumns<DataSource> = [
  { type: 'selection' },
  { title: 'ID', key: 'id', width: 80 },
  { title: '数据源名称', key: 'name', ellipsis: { tooltip: true } },
  {
    title: '数据源类型',
    key: 'type',
    width: 120,
    render: (row: DataSource) => {
      const typeMap: Record<string, { label: string; type: any }> = {
        MYSQL: { label: 'MySQL', type: 'success' },
        ORACLE: { label: 'Oracle', type: 'warning' },
        POSTGRESQL: { label: 'PostgreSQL', type: 'info' },
        SQLSERVER: { label: 'SQL Server', type: 'default' },
        DAMENG: { label: '达梦', type: 'default' },
        KINGBASE: { label: '人大金仓', type: 'default' },
        DORIS: { label: 'Doris', type: 'primary' }
      };
      const config = typeMap[row.type] || { label: row.type, type: 'default' };
      return h(NTag, { type: config.type }, { default: () => config.label });
    }
  },
  { title: '主机地址', key: 'host', ellipsis: { tooltip: true } },
  { title: '端口', key: 'port', width: 80 },
  { title: '数据库名', key: 'databaseName', ellipsis: { tooltip: true } },
  {
    title: '状态',
    key: 'status',
    width: 80,
    render: (row: DataSource) => {
      return h(NTag, { type: row.status === 1 ? 'success' : 'error' }, { default: () => (row.status === 1 ? '启用' : '禁用') });
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render: (row: DataSource) => {
      return h(
        NSpace,
        {},
        {
          default: () => [
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleTest(row)
              },
              { default: () => '测试' }
            ),
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleEdit(row)
              },
              { default: () => '编辑' }
            ),
            h(
              NButton,
              {
                size: 'small',
                type: 'error',
                onClick: () => handleDelete(row)
              },
              { default: () => '删除' }
            )
          ]
        }
      );
    }
  }
];

// 对话框相关
const showModal = ref(false);
const modalTitle = ref('新增数据源');
const formRef = ref<FormInst | null>(null);
const formData = ref<DataSource>({
  name: '',
  type: 'MYSQL' as DataSourceType,
  host: '',
  port: undefined,
  databaseName: '',
  username: '',
  password: '',
  status: 1,
  remark: ''
});

// 表单验证规则
const formRules: FormRules = {
  name: [{ required: true, message: '请输入数据源名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择数据源类型', trigger: 'change' }],
  host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getDataSourceList({ pageNum: pagination.page, pageSize: pagination.pageSize });
    if (res.data) {
      dataSource.value = res.data.rows;
      pagination.itemCount = res.data.total;
    }
  } catch (error) {
    window.$message?.error('获取数据源列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理选择
const handleCheck = (keys: number[]) => {
  selectedRowKeys.value = keys;
};

// 新增
const handleAdd = () => {
  modalTitle.value = '新增数据源';
  formData.value = {
    name: '',
    type: 'MYSQL' as DataSourceType,
    host: '',
    port: undefined,
    databaseName: '',
    username: '',
    password: '',
    status: 1,
    remark: ''
  };
  showModal.value = true;
};

// 编辑
const handleEdit = (row: DataSource) => {
  modalTitle.value = '编辑数据源';
  formData.value = { ...row };
  showModal.value = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    const api = formData.value.id ? updateDataSource : addDataSource;
    await api(formData.value);
    window.$message?.success(formData.value.id ? '修改成功' : '新增成功');
    showModal.value = false;
    fetchData();
  } catch (error) {
    // 验证失败或API调用失败
  }
};

// 测试连接（表格中的测试按钮）
const handleTest = async (row: DataSource) => {
  try {
    const res = await testDataSourceConnection(row.id!);
     console.log(res);
    if (res.response.data.code===200) {
      window.$message?.success('连接测试成功');
    } else {
      window.$message?.error('连接测试失败');
    }
  } catch (error) {
    window.$message?.error('连接测试失败');
  }
};

// 测试连接（表单中的测试按钮）
const handleTestConnection = async () => {
  try {
    await formRef.value?.validate();
    const res = await testConnection({
      type: formData.value.type,
      host: formData.value.host!,
      port: formData.value.port!,
      databaseName: formData.value.databaseName,
      username: formData.value.username!,
      password: formData.value.password!
    });
   if (res.response.data.code===200) {
      window.$message?.success('连接测试成功');
    } else {
      window.$message?.error('连接测试失败2');
    }
  } catch (error) {
    // 验证失败或API调用失败
  }
};

// 删除
const handleDelete = (row: DataSource) => {
  window.$dialog?.warning({
    title: '确认删除',
    content: `确定要删除数据源"${row.name}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deleteDataSource(row.id!);
        window.$message?.success('删除成功');
        fetchData();
      } catch (error) {
        window.$message?.error('删除失败');
      }
    }
  });
};

// 批量删除
const handleBatchDelete = () => {
  window.$dialog?.warning({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个数据源吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deleteDataSource(selectedRowKeys.value);
        window.$message?.success('删除成功');
        selectedRowKeys.value = [];
        fetchData();
      } catch (error) {
        window.$message?.error('删除失败');
      }
    }
  });
};

// 刷新
const handleRefresh = () => {
  fetchData();
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.datasource-container {
  height: 100%;
}
</style>
